<!-- Licensed under a BSD license. See license.html for license -->
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
    <title>WebGL - 2D Geometry Translate Better</title>
    <link type="text/css" href="../resources/webgl-tutorials.css" rel="stylesheet" />
    <style>
        #ui {
            width: 200px;
        }
    </style>
</head>

<body>
    <div id="info">
        <a href="https://webglfundamentals.org/webgl/lessons/zh_cn/webgl-2d-translation.html" target="_blank">WebGL
            二维平移</a>
        <div class="description">
            Drag sliders to translate.
        </div>
    </div>
    <canvas id="canvas"></canvas>
    <div id="uiContainer">
        <div id="ui">
            <div id="x"></div>
            <div id="y"></div>
        </div>
    </div>
</body>
<!-- vertex shader -->
<script id="2d-vertex-shader" type="x-shader/x-vertex">
attribute vec2 a_position;

uniform vec2 u_resolution;
uniform vec2 u_translation;

void main() {
   // 加上平移量
   vec2 position = a_position + u_translation;
   // vec2 position = a_position;//如果不设置平移，进度条拖动无反应

   // 从像素坐标转换到 0.0 到 1.0
   vec2 zeroToOne = position / u_resolution;

   // convert from 0->1 to 0->2
   vec2 zeroToTwo = zeroToOne * 2.0;

   // convert from 0->2 to -1->+1 (clipspace)
   vec2 clipSpace = zeroToTwo - 1.0;

   gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
}
</script>
<!-- fragment shader -->
<script id="2d-fragment-shader" type="x-shader/x-fragment">
precision mediump float;

uniform vec4 u_color;

void main() {
   gl_FragColor = u_color;
}
</script>
<!--
for most samples webgl-utils only provides shader compiling/linking and
canvas resizing because why clutter the examples with code that's the same in every sample.
See http://webglfundamentals.org/webgl/lessons/webgl-boilerplate.html
and http://webglfundamentals.org/webgl/lessons/webgl-resizing-the-canvas.html
for webgl-utils, m3, m4, and webgl-lessons-ui.
-->
<script src="../resources/webgl-utils.js"></script>
<script src="../resources/webgl-lessons-ui.js"></script>
<script>
    "use strict";

    function main() {
        // Get A WebGL context
        /** @type {HTMLCanvasElement} */
        var canvas = document.getElementById("canvas");
        var gl = canvas.getContext("webgl");
        if (!gl) {
            return;
        }

        // setup GLSL program
        var program = webglUtils.createProgramFromScripts(gl, ["2d-vertex-shader", "2d-fragment-shader"]);
        gl.useProgram(program);

        // look up where the vertex data needs to go.
        var positionLocation = gl.getAttribLocation(program, "a_position");

        // lookup uniforms
        var resolutionLocation = gl.getUniformLocation(program, "u_resolution");
        var colorLocation = gl.getUniformLocation(program, "u_color");
        var translationLocation = gl.getUniformLocation(program, "u_translation");

        // 创建一个存放位置信息的缓冲
        var positionBuffer = gl.createBuffer();
        // 绑定到 ARRAY_BUFFER (简单的理解为 ARRAY_BUFFER = positionBuffer)
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        // Put geometry data into buffer
        setGeometry(gl);

        var translation = [0, 0];
        var color = [Math.random(), Math.random(), Math.random(), 1];

        drawScene();

        // Setup a ui.
        webglLessonsUI.setupSlider("#x", { slide: updatePosition(0), max: gl.canvas.width });
        webglLessonsUI.setupSlider("#y", { slide: updatePosition(1), max: gl.canvas.height });

        function updatePosition(index) {
            return function (event, ui) {
                translation[index] = ui.value;
                drawScene();
            };
        }

        // 绘制场景
        function drawScene() {
            webglUtils.resizeCanvasToDisplaySize(gl.canvas);

            // Tell WebGL how to convert from clip space to pixels
            gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);

            // Clear the canvas.
            gl.clear(gl.COLOR_BUFFER_BIT);

            // Tell it to use our program (pair of shaders)
            gl.useProgram(program);

            // Turn on the attribute
            gl.enableVertexAttribArray(positionLocation);

            // Bind the position buffer.
            gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

            // Tell the attribute how to get data out of positionBuffer (ARRAY_BUFFER)
            var size = 2;          // 2 components per iteration
            var type = gl.FLOAT;   // the data is 32bit floats
            var normalize = false; // don't normalize the data
            var stride = 0;        // 0 = move forward size * sizeof(type) each iteration to get the next position
            var offset = 0;        // start at the beginning of the buffer
            gl.vertexAttribPointer(
                positionLocation, size, type, normalize, stride, offset);

            // set the resolution
            gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height);

            // set the color
            gl.uniform4fv(colorLocation, color);

            // 设置平移
            gl.uniform2fv(translationLocation, translation);

            // 绘制矩形
            var primitiveType = gl.TRIANGLES;
            var offset = 0;
            var count = 18;  // 6 triangles in the 'F', 3 points per triangle
            gl.drawArrays(primitiveType, offset, count);
        }
    }

    // 在缓冲存储构成 'F' 的值
    // 与上一个示例不同
    // 这里只保留原始顶点，拖动滑块不对顶点做处理，而是将滑块的值传入着色器
    function setGeometry(gl) {
        gl.bufferData(
            gl.ARRAY_BUFFER,
            new Float32Array([
                // 左竖
                0, 0,
                30, 0,
                0, 150,
                0, 150,
                30, 0,
                30, 150,

                // 上横
                30, 0,
                100, 0,
                30, 30,
                30, 30,
                100, 0,
                100, 30,

                // 中横
                30, 60,
                67, 60,
                30, 90,
                30, 90,
                67, 60,
                67, 90,
            ]),
            gl.STATIC_DRAW);
    }

    main();
</script>

</html>